package com.suixun.dao.redis;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
/**
 * 功能描述:  缓存dao
 * @author jacky
 * @date 2018年1月6日下午4:06:02
 */
@Repository
public class RedisDao {

	private final static Logger logger = LoggerFactory.getLogger(RedisDao.class);

	@Autowired
	protected RedisTemplate<Object, Object> redisTemplate;

	/**
	 * 
	 * 功能描述: 批量清除缓存,如key=banner*,则清除前缀为banner的所有缓存
	 * @param key
	 */
	public void flushCaches(String key) {
		try {
			redisTemplate.execute(new RedisCallback<Long>() {
				@Override
				public Long doInRedis(RedisConnection connection) throws DataAccessException {
					Set<byte[]> keys = connection.keys(key.getBytes());
					if (keys == null || keys.size() == 0)
						return 1L;
					byte[][] rawKeys = new byte[keys.size()][];
					int i = 0;
					for (byte[] key : keys) {
						rawKeys[i++] = key;
					}
					connection.del(rawKeys);
					return 1L;
				}
			});
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
}
